package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {
    @Autowired
    public ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    public SkuFeign skuFeign;
    @Autowired
    public ESManagerMapper esManagerMapper;
    //创建索引库结构
    @Override
    public void createMappingAndIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    //全部
    @Override
    public void importAll() {
        //查询spu全部数据
        List<Sku> skuList = skuFeign.findSkuListBySpuId("all");
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //将spuList集合转为json
        String json = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfos = JSON.parseArray(json, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            //将规格信息转化为map
            Map specmap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specmap);
        }
        //导入索引库
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void importDataBySpuId(String spuId) {
        //查询spu全部数据
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //将spuList集合转为json
        String json = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfos = JSON.parseArray(json, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfos) {
            //将规格信息转化为map
            Map specmap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specmap);
        }
        //添加到索引库
        esManagerMapper.saveAll(skuInfos);
    }

    @Override
    public void delDataBySpuId(String spuId) {
        //查询spu全部数据
        List<Sku> skuList = skuFeign.findSkuListBySpuId(spuId);
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        for (Sku sku : skuList) {
            //根据id 从索引库中删除
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
